const checkLogin = () => {
  const token = wx.getStorageSync('token');
  const userInfo = wx.getStorageSync('userInfo');
  return !!(token && userInfo);
};

const getToken = () => {
  return wx.getStorageSync('token');
};

const getUserInfo = () => {
  return wx.getStorageSync('userInfo');
};

const setLoginState = (data) => {
  if (!data || !data.token) {
    console.error('Invalid login data:', data);
    return false;
  }
  const { token, userInfo, openid } = data;
  wx.setStorageSync('token', token);
  wx.setStorageSync('userInfo', userInfo);
  wx.setStorageSync('openid', openid);
  return true;
};

const clearLoginState = () => {
  wx.removeStorageSync('token');
  wx.removeStorageSync('userInfo');
  wx.removeStorageSync('openid');
};

const autoLogin = async () => {
  try {
    const loginRes = await wx.login();
    if (!loginRes.code) {
      console.error('Failed to get login code');
      return false;
    }

    const res = await new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:3000/api/login',
        method: 'POST',
        data: { code: loginRes.code },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.token) {
            resolve(res.data);
          } else {
            reject(new Error('Invalid login response'));
          }
        },
        fail: reject
      });
    });

    return setLoginState(res);
  } catch (e) {
    console.error('自动登录失败:', e);
    return false;
  }
};

module.exports = {
  checkLogin,
  getToken,
  getUserInfo,
  setLoginState,
  clearLoginState,
  autoLogin
}; 